﻿var http = require('http');
var express = require('express');
var swig = require('swig');
var ws = require("nodejs-websocket");
var date = require("silly-datetime");

var connect = [];
{
    var server = ws.createServer(function (conn) {
        console.log("New connection")
        conn.on("text", function (str) {
            server.connections.forEach(function (conn) {
                console.log(date.format(new Date(),'YYYY-MM-DD HH:mm:ss') + "广播消息:"+str)
                conn.sendText(str)
            })
/*            console.log("接收客户端发送的数据:"+str)
            conn.sendText("hello client")*/
        })
        conn.on("close", function (code, reason) {//链接断开
            console.log("Connection closed")
        })

        conn.on('connect', function(code) {//链接成功
            console.log('开启连接', code)
        })

        conn.on('error', function(code) {//是指客户端异常关闭
            console.log('异常关闭', code)
        })
    }).listen(8080);
    console.log("监听8080");

    http.ClientRequest.prototype.setTimeout = function (timeout, callback) {
        var self = this;
        if (callback) {
            self.on('timeout', callback);
        }
        self.connection.setTimeout(timeout, function () {
            self.abort();
            self.emit('timeout');
        });
    };
    var app = express();
    app.engine('html', swig.renderFile);
    app.set('views', './tpl');
    app.set('view engine', 'html');
    swig.setDefaults({cache: false});
    app.use('/tpl', express.static(__dirname + '/tpl'));
    app.listen(8085);


    app.get("*", function (req, res, next) {
        res.render('index.html')
    });


    module.exports = app;
}//网页操作的代码

